﻿
namespace Huirui.Cavan.Application.MainBoundedContext.SystemModule
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Web;
    using Spring.Context;
    using Spring.Context.Support;
    using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
    using Huirui.Cavan.Core.Extension;
    using Huirui.Cavan.Core.Message;

    public class SecurityProvider
    {
        #region members
        CurrentUserProvider _currentUserProvider;
        #endregion members

        public SecurityProvider()
        {
            Init();
        }

        public virtual UserAccount GetUserAccount()
        {
            return CurrentUserProvider.UserAccount;
        }

        public virtual Corporation GetCorporation()
        {
            return CurrentUserProvider.Corporation;
        }

        public virtual Role GetCurrentUserRole()
        {
            return CurrentUserProvider.UserRole;
        }

        public virtual IList<SysController> GetGrantedControllers()
        {
            Role currentUserRole = RoleAppService.GetById(GetCurrentUserRole().Id);
            if (currentUserRole.IsNull())
            {
                return new List<SysController>();
            }
            return currentUserRole.Controllers;
        }

        public virtual IList<SysAction> GetGrantedActions()
        {
            Role currentUserRole = RoleAppService.GetById(GetCurrentUserRole().Id);
            if (currentUserRole.IsNull())
            {
                return new List<SysAction>();
            }
            return currentUserRole.Actions;
        }
        #region IoC
        IRoleAppService RoleAppService { get; set; }

        public virtual CurrentUserProvider CurrentUserProvider
        {
            protected get
            {
                if (_currentUserProvider.IsNull())
                {
                    _currentUserProvider =  new CurrentUserProvider();
                }
                return _currentUserProvider;
            }
            set { _currentUserProvider = value; }
        }

        void Init()
        {
            IApplicationContext ctx = ContextRegistry.GetContext();
            RoleAppService = ctx.GetObject("RoleAppService") as IRoleAppService;
            IList<AppMessage> lstMessage = new List<AppMessage>();
            RoleAppService.Messages = lstMessage;
        }
        #endregion IoC
    }
}